import { _decorator, Component, Node, Sprite, UITransform, v3, Vec3, Vec2 } from "cc";
import { BaseComponent } from "../../core/component/BaseComponent";
import Toast from "../../core/component/Toast";
import { Engine } from "../../core/Engine";
import { dataManager } from "../data/DataManager";
import { ATTACK_OR_DEFENSE, DispatchArmyInfo } from "../data/SoldierData";
import { EVENT_NAME, GAME_DATA } from "../GameConstant";
const { ccclass, property } = _decorator;

export enum ArmyState {
    GARRISON,
    MOVE,
}
@ccclass("WorldArmy")
export class WorldArmy extends BaseComponent {
    @property({ type: Sprite, displayName: "首领形象" })
    avatar!: Sprite;

    armyId!: string; // 出兵队列的id
    startCityId!: string; // 出发城
    currentArmyCityId!: string;
    armyState = ArmyState.GARRISON;
    armyInfoData: DispatchArmyInfo | undefined;
    armySpeed = GAME_DATA.ARMY_SPEED;

    armySpeedX = 0;
    armySpeedY = 0;

    gapTime = 1;

    targetCity!: { cityId: string; pos: Vec3 };
    // movePaths: string[] | undefined;
    onLoad() {
        Engine.eventManager.on(
            EVENT_NAME.FAST_TO_TARGET_CITY,
            (dispatchArmyId: string, toCityId: string) => {
                if (dispatchArmyId === this.armyId) {
                    this.fastToTargetCity(toCityId);
                }
            },
            this
        );

        Engine.eventManager.on(
            EVENT_NAME.STOP_DISPATCH_ARMY,
            (dispatchArmyId: string, cityId: string) => {
                if (dispatchArmyId === this.armyId) {
                    // 结束移动
                    this.armyState = ArmyState.GARRISON;
                    this.node.removeFromParent();
                }
            },
            this
        );

        Engine.eventManager.on(
            EVENT_NAME.ARMY_CHANGE_CURRENT_CITY,
            (dispatchArmyId: string, armyData: DispatchArmyInfo) => {
                if (dispatchArmyId === this.armyId) {
                    this.armyInfoData = armyData;
                    this.goCity();
                }
            },
            this
        );
    }

    start() {
        // [3]
    }

    setData(armyId: string, armyData: DispatchArmyInfo) {
        this.armyId = armyId;
        this.armyInfoData = armyData;
        // const paths = dataManager.dataMap.findPath(armyData.fromCityId, armyData.toCityId, BELONG_TYPE.SELF_SIDE);
        const armyPos: Vec2 = dataManager.dataSoldier.calculateCurrentArmyInfoData(armyData)!;
        // const [cityX, cityY] = armyData.armyPos.split("-");
        this.node.position = v3(armyPos.x, armyPos.y, 0);

        this.startCityId = armyData.currentCityId;
        this.currentArmyCityId = armyData.currentCityId;
        // this.movePaths = leftPaths;
        // this.movePaths!.shift()!;
        this.goCity();
        this.setArmyAvatar();
    }

    // 攻击形象还是防守形象
    setArmyAvatar() {
        this.node.getChildByName("defense")!.active = false;
        this.node.getChildByName("attack")!.active = false;
        let hasAttackSoldier = false;
        let hasDefenseSoldier = false;
        for (const soldierId in this.armyInfoData!.soldiers) {
            if (hasAttackSoldier && hasDefenseSoldier) {
                break;
            }
            if (dataManager.dataSoldier.getSoldierCfgData(soldierId).attackOrDefense === ATTACK_OR_DEFENSE.ATTACK) {
                hasAttackSoldier = true;
            }
            if (dataManager.dataSoldier.getSoldierCfgData(soldierId).attackOrDefense === ATTACK_OR_DEFENSE.DEFENSE) {
                hasDefenseSoldier = true;
            }
        }
        if (hasAttackSoldier) {
            // 攻击
            this.node.getChildByName("attack")!.active = true;
        }
        if (hasDefenseSoldier) {
            // 防御
            this.node.getChildByName("defense")!.active = true;

            this.node.active = false;
        }
    }

    // 前往城池
    goCity() {
        if (!this.currentArmyCityId) {
            console.error("状态有误");
            return;
        }
        this.currentArmyCityId = this.armyInfoData!.currentCityId;
        const toCityId = this.armyInfoData!.nextCityId;
        let cityLine = dataManager.dataMap.getTwoCityLine(this.currentArmyCityId, toCityId);
        this.startMoveToTargetCity(this.currentArmyCityId, toCityId, cityLine);

        // if (this.movePaths && this.movePaths.length > 0) {
        //     const toCityId: string = this.movePaths!.shift()!;
        //     let cityLine = dataManager.dataMap.terrainLines[this.currentArmyCityId + "-" + toCityId];
        //     if (!cityLine) {
        //         cityLine = dataManager.dataMap.terrainLines[toCityId + "-" + this.currentArmyCityId];
        //         if (!cityLine) {
        //             Toast.showToast("城市间不联通:" + this.currentArmyCityId + "-" + toCityId);
        //             this.endMoveToTargetCity();
        //             return;
        //         } else {
        //             const cityLineInfo = { startPos: cityLine.toPos, toPos: cityLine.startPos, len: cityLine.len };
        //             this.startMoveToTargetCity(toCityId, cityLineInfo);
        //         }
        //     } else {
        //         this.startMoveToTargetCity(toCityId, cityLine);
        //     }
        // } else {
        //     this.endMoveToTargetCity();
        // }
    }

    startMoveToTargetCity(
        startCityId: string,
        toCityId: string,
        cityLine: { startPos: string; toPos: string; len: number }
    ) {
        this.armyState = ArmyState.MOVE;
        const speedTime = cityLine.len / this.armySpeed;
        const startCityDetail = dataManager.dataMap.getCityDetail(startCityId);
        const toCityDetail = dataManager.dataMap.getCityDetail(toCityId);
        const fromCityPosXY = startCityDetail!.pos.split("-");
        const toCityPosXY = toCityDetail!.pos.split("-");
        this.armySpeedX = (Number(toCityPosXY[0]) - Number(fromCityPosXY[0])) / speedTime;
        this.armySpeedY = (Number(toCityPosXY[1]) - Number(fromCityPosXY[1])) / speedTime;

        this.targetCity = { cityId: toCityId, pos: v3(Number(toCityPosXY[0]), Number(toCityPosXY[1]), 0) };
        if (!this.targetCity) {
            console.error("this.targetCity", startCityId, toCityId, cityLine);
        }
    }

    // 直接移动到目的地
    fastToTargetCity(toCityId: string) {
        // this.movePaths = [];
        const toCityDetail = dataManager.dataMap.getCityDetail(toCityId);
        const toCityPosXY = toCityDetail!.pos.split("-");
        this.targetCity = { cityId: toCityId, pos: v3(Number(toCityPosXY[0]), Number(toCityPosXY[1]), 0) };
        this.node.position = this.targetCity.pos;
    }

    update(dt: number) {
        if (this.armyState === ArmyState.MOVE) {
            const orinPos = this.node.position;
            if (
                Math.abs(this.targetCity.pos.x - orinPos.x) <= Math.abs(this.armySpeedX * dt) ||
                Math.abs(this.targetCity.pos.y - orinPos.y) <= Math.abs(this.armySpeedY * dt)
            ) {
                this.node.position = this.targetCity.pos;
            } else {
                this.node.position = this.node.position.clone().add(v3(this.armySpeedX * dt, this.armySpeedY * dt, 0));
            }

            // this.gapTime += dt;
            // if (this.gapTime > 1) {
            //     this.gapTime -= 1;
            //     dataManager.dataPlayer.updateDispatchArmyData(
            //         this.armyId,
            //         this.currentArmyCityId,
            //         v3(Math.floor(this.node.position.x), Math.floor(this.node.position.y), 0),
            //         1
            //     );
            // }
        }
    }
}
